using System;
using System.Windows.Forms;
using System.Data.SQLite;
using System.IO;

namespace LoginSystem
{
    public partial class LoginForm : Form
    {
        private const string DbFile = "users.db";
        private string connectionString;

        public LoginForm()
        {
            InitializeComponent();
            InitializeDatabase();
        }

        private void InitializeComponent()
        {
            this.Text = "用户登录";
            this.Width = 400;
            this.Height = 300;
            this.StartPosition = FormStartPosition.CenterScreen;

            // 用户名标签
            Label lblUsername = new Label();
            lblUsername.Text = "用户名：";
            lblUsername.Location = new System.Drawing.Point(50, 50);
            lblUsername.AutoSize = true;

            // 用户名输入框
            TextBox txtUsername = new TextBox();
            txtUsername.Name = "txtUsername";
            txtUsername.Location = new System.Drawing.Point(150, 50);
            txtUsername.Width = 200;

            // 密码标签
            Label lblPassword = new Label();
            lblPassword.Text = "密码：";
            lblPassword.Location = new System.Drawing.Point(50, 90);
            lblPassword.AutoSize = true;

            // 密码输入框
            TextBox txtPassword = new TextBox();
            txtPassword.Name = "txtPassword";
            txtPassword.Location = new System.Drawing.Point(150, 90);
            txtPassword.Width = 200;
            txtPassword.PasswordChar = '*';

            // 登录按钮
            Button btnLogin = new Button();
            btnLogin.Text = "登录";
            btnLogin.Location = new System.Drawing.Point(150, 140);
            btnLogin.Width = 80;
            btnLogin.Click += new EventHandler(BtnLogin_Click);

            // 注册按钮
            Button btnRegister = new Button();
            btnRegister.Text = "注册";
            btnRegister.Location = new System.Drawing.Point(270, 140);
            btnRegister.Width = 80;
            btnRegister.Click += new EventHandler(BtnRegister_Click);

            // 添加控件到窗体
            this.Controls.AddRange(new Control[] {
                lblUsername, txtUsername,
                lblPassword, txtPassword,
                btnLogin, btnRegister
            });
        }

        private void InitializeDatabase()
        {
            connectionString = $"Data Source={DbFile};Version=3;";
            if (!File.Exists(DbFile))
            {
                SQLiteConnection.CreateFile(DbFile);
                using (var connection = new SQLiteConnection(connectionString))
                {
                    connection.Open();
                    string sql = @"
                        CREATE TABLE Users (
                            Id INTEGER PRIMARY KEY AUTOINCREMENT,
                            Username TEXT NOT NULL UNIQUE,
                            Password TEXT NOT NULL,
                            CreateTime DATETIME DEFAULT CURRENT_TIMESTAMP
                        )";
                    using (var command = new SQLiteCommand(sql, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
            }
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            string username = Controls.Find("txtUsername", true)[0].Text;
            string password = Controls.Find("txtPassword", true)[0].Text;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("用户名和密码不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (ValidateUser(username, password))
            {
                MessageBox.Show("登录成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // 这里可以打开主窗体
                ShowMainForm();
            }
            else
            {
                MessageBox.Show("用户名或密码错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnRegister_Click(object sender, EventArgs e)
        {
            RegisterForm registerForm = new RegisterForm(connectionString);
            registerForm.ShowDialog();
        }

        private bool ValidateUser(string username, string password)
        {
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                string sql = "SELECT COUNT(*) FROM Users WHERE Username = @Username AND Password = @Password";
                using (var command = new SQLiteCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@Username", username);
                    command.Parameters.AddWithValue("@Password", password);
                    int count = Convert.ToInt32(command.ExecuteScalar());
                    return count > 0;
                }
            }
        }

        private void ShowMainForm()
        {
            MainForm mainForm = new MainForm();
            this.Hide();
            mainForm.ShowDialog();
            this.Close();
        }
    }
}